#include <iostream>
#include <cmath>
#include "dyn_roots_newtonRaphson.h"

/*! Constructor. */

NewtonRaphson::NewtonRaphson(Functor &func,
                             Functor &dfunc,
                             double initialGuess,
                             const double tol,
                             const int maxNumberIterations)
    : function(func), derivative(dfunc)
{
    setInitialValue(initialGuess);
    setTolerance(tol);
    setMaxIterations(maxNumberIterations);
}

/*! We apply the Newton-Raphson algorithm.
 * The function returns an error code.
 * If it returns 0, everything went as planned.
 * If it returns 1, the algorithm failed to convergence
 * within the maximum number of iterations.
 */
int NewtonRaphson::solve()
{
    // We declare the return value
    int returnCode;

    // We start the clock.
    start = clock();

    // We set the root to be the initial guess.
    // This value will be updated by the algorithm.
    root = initialValue;

    // Actual numerical computation of the root.
    for (int i=0;i<maxIterations;i++)
    {
        double dx = function(root)/derivative(root);
        root -= dx;

        // We increment the iterations counter.
        iterations++;


        if (fabs(dx) < tolerance)
        {
            returnCode = 0;
            break;
        }
        else
            returnCode = 1;
    }

    end = clock();
    processorTime = ((double) (end-start))/ CLOCKS_PER_SEC;
    return returnCode;
}
